package com.mz361.common.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.util.Timeout;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取HttpServlet子对象
 *
 * @author niceale * @date 2023/10/15
 */
@Slf4j
public class HttpServletUtil {
    /**
     * 获取ServletRequestAttributes对象
     */
    public static ServletRequestAttributes getServletRequest() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取HttpServletRequest对象
     */
    public static HttpServletRequest getRequest() {
        return getServletRequest().getRequest();
    }

    /**
     * 获取HttpServletResponse对象
     */
    public static HttpServletResponse getResponse() {
        return getServletRequest().getResponse();
    }

    /**
     * 获取请求参数
     */
    public static String getParameter(String param) {
        return getRequest().getParameter(param);
    }

    /**
     * 获取请求参数，带默认值
     */
    public static String getParameter(String param, String defaultValue) {
        String parameter = getRequest().getParameter(param);
        return StringUtils.isEmpty(parameter) ? defaultValue : parameter;
    }

    /**
     * 获取请求参数转换为int类型
     */
    public static Integer getParameterInt(String param) {
        return Integer.valueOf(getRequest().getParameter(param));
    }

    /**
     * 获取请求参数转换为int类型，带默认值
     */
    public static Integer getParameterInt(String param, Integer defaultValue) {
        return Integer.valueOf(getParameter(param, String.valueOf(defaultValue)));
    }


    /**
     * 发送get请求-无参
     *
     * @param url     请求url
     * @param headers 请求头
     * @return 响应体
     */
    public static String sendGetRequestNoParams(String url, Map<String, String> headers) {
        Long startTime = System.currentTimeMillis();
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头
        if (headers != null) {
            headers.forEach(httpGet::setHeader);
        }

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("HttpGeturl:{},status:{},time:{}ms,headers:{}", url, response.getCode(), System.currentTimeMillis() - startTime, JSONObject.toJSONString(headers));

        }
        return null;
    }


    /**
     * 发送get请求
     *
     * @param url       请求url
     * @param paramsMap 参数
     * @param headers   请求头
     * @return 响应体
     */
    public static String sendGetRequestNeedParams(String url, Map<String, String> paramsMap, Map<String, String> headers) {
        Long startTime = System.currentTimeMillis();
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 参数拼接
        List<String> params = new ArrayList<>();
        paramsMap.forEach((key, value) -> {
            try {
                // 字符数据最好encoding以下;这样一来，某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
                params.add(key + "=" + URLEncoder.encode(value, "utf-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        });
        String paramsStr = String.join("&", params);
        if (StringUtil.notEmpty(paramsStr)) {
            url += "?" + paramsStr;
        }
        // 创建Get请求
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头
        if (headers != null) {
            headers.forEach(httpGet::setHeader);
        }

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(Timeout.ofDays(5000))
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(Timeout.ofDays(5000))
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();
            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("HttpGeturl:{},status:{},time:{}ms,params:{},headers:{}", url, response.getCode(), System.currentTimeMillis() - startTime, JSONObject.toJSONString(paramsMap), JSONObject.toJSONString(headers));
        }
        return null;
    }

    /**
     * 发送post请求
     *
     * @param url             请求url
     * @param requestDataJson 请求体的数据，json格式
     * @param headers         请求头
     * @return 响应体
     */
    public static String sendPostRequestByJson(String url, String requestDataJson, Map<String, String> headers) {
        Long startTime = System.currentTimeMillis();
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 将json数据放入entity中
        StringEntity entity = new StringEntity(requestDataJson, ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        if (headers != null) {
            headers.forEach(httpPost::setHeader);
        }
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("HttpPosturl:{},status:{},time:{}ms,data:{},headers:{}", url, response.getCode(), System.currentTimeMillis() - startTime, requestDataJson, JSONObject.toJSONString(headers));
        }
        return null;
    }

    public static InputStream sendPostReqtByJson(String url, String requestDataJson, Map<String, String> headers) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 将json数据放入entity中
        StringEntity entity = new StringEntity(requestDataJson, ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        if (headers != null) {
            headers.forEach(httpPost::setHeader);
        }
        // 响应模型
        CloseableHttpResponse response = null;
        // 由客户端执行(发送)Post请求
        response = httpClient.execute(httpPost);
        // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        return responseEntity.getContent();


    }


    /**
     * 发送post请求，表单形式，请求体放对象，而不是json串
     *
     * @param url     请求url
     * @param params  请求体中的参数
     * @param headers 请求头
     * @return
     */
    public static String sendPostRequestByForm(String url, Map<String, String> params, Map<String, String> headers) {
        Long startTime = System.currentTimeMillis();
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        // 将请求数据放置请求体中
        List<BasicNameValuePair> paramList = new ArrayList<>();
        params.forEach((key, value) -> {
            paramList.add(new BasicNameValuePair(key, value));
        });
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(formEntity);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        if (headers != null) {
            headers.forEach(httpPost::setHeader);
        }
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("HttpPosturl:{},status:{},time:{}ms,params:{},headers:{}", url, response.getCode(), System.currentTimeMillis() - startTime, JSONObject.toJSONString(params), JSONObject.toJSONString(headers));
        }
        return null;
    }

    public static InputStream sendPostByJson(String urlStr, String requestDataJson, Map<String, String> headers) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法，默认为GET
            connection.setRequestMethod("POST");
//            connection.setRequestProperty("Transfer-Encoding", "chunked");
            // 发送POST请求必须设置
            for (String key : headers.keySet()) {
                connection.setRequestProperty(key, headers.get(key));
            }
            connection.setDoOutput(true);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.writeBytes(requestDataJson);
                wr.flush();
            }
            int responseCode = connection.getResponseCode();
            System.out.println("POST Response Code :: " + responseCode);
            // 获取输入流
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (connection != null) {
                    connection.connect();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
